# encoding=utf-8
# -------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:
#
# Created:     16/05/2022
# Copyright:   (c)  2022
# Licence:     <your licence>
# -------------------------------------------------------------------------------
import os
import json
class FireWallConfig:
    target = ''
    src = ''
    dest = ''
    name = ''
    proto = ''
    src_dport = ''
    dest_ip = ''
    dest_port = ''

config_path = '/etc/config/firewall'
def read_config():
    path = config_path
    lst = []
    with open(path, 'r', -1, 'utf8') as of:
        config = None
        for s in of:
            if not s.strip():
                continue
            words = s.strip().split(None, 2)
            if words[0] == 'config':
                if config:
                    lst.append(config)
                    config = None
                if words[1] == 'redirect':
                    config = FireWallConfig()
            if words[0] == 'option' and config:
                field = words[1]
                val = words[2].strip("'")
                setattr(config, field, val)
        if config:
            lst.append(config)
    return lst

def write_iptables(config_lst):
    config = FireWallConfig()
    sh = '/tmp/ipv6_fire.sh'
    doit = False
    with open(sh, 'w', encoding='utf8') as of:
        of.write('killall socat\n')
        for config in config_lst:
            print(config.dest_port, config.proto)
            if 'tcp' in config.proto:
                cmd = 'ip6tables -I zone_wan_input 1 -p tcp --dport %s -j ACCEPT '%config.src_dport
                of.write(cmd + '\n')
                cmd = 'socat TCP6-LISTEN:%s,reuseaddr,fork TCP4:%s:%s &'%(config.src_dport, config.dest_ip, config.dest_port)
                of.write(cmd + '\n')
            if 'udp' in config.proto:
                cmd = 'ip6tables -I zone_wan_input 1 -p udp --dport %s -j ACCEPT '%config.src_dport
                of.write(cmd + '\n')
                cmd = 'socat UDP6-LISTEN:%s,reuseaddr,fork UDP4:%s:%s &'%(config.src_dport, config.dest_ip, config.dest_port)
                of.write(cmd + '\n')
            doit = True
    if doit:
        exec_cmd('bash ' + sh)

def exec_cmd(cmd):
    #print(cmd)
    os.system(cmd)

def main():
    data = {'mtime': 0}
    # json_path = os.path.abspath(__file__)
    # json_path = os.path.dirname(json_path)
    json_path = os.path.join('/tmp', 'data.json')
    if os.path.exists(json_path):
        with open(json_path, 'r', encoding='utf8') as of:
            data = json.load(of)
    mtime = os.path.getmtime(config_path)
    if data.get('mtime', 0) != mtime:
        write_iptables(read_config())
        data['mtime'] = mtime
        with open(json_path, 'w', encoding='utf8') as of:
            json.dump(data, of)

main()
